<?php

namespace App\Http\Middleware;

use App\Http\Controllers\JwtController;
use Closure;
use Illuminate\Http\Request;

/**
 * 验证前台请求数据 JWT token
 */
class CheckJwtHeaderToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        //  return $next($request); //验证通过


        $auth_token = $this->getToken($request);

        if ($auth_token == 'cdbottle123') {
            return $next($request); //验证通过  测试时 绕过验证
        }
        if (empty($auth_token)) {
            return  response()->json(['code' => 205, 'msg' => '认证失败invalid_token']);
        }

        //不是微信环境，不允许调用此类接口(如果jwt 是 cdbottle123  可以绕过此验证)
        $user_agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($user_agent, 'MicroMessenger') === false) {
            // 当前请求不是来自微信环境
            return  response()->json(['code' => 201, 'msg' => '网络错误']);
        }

        //验证token有效期
        try {
            $jwtControllerObj = new JwtController();
            $token_msg = $jwtControllerObj->verifyToken($auth_token);
            if ($token_msg !== true) {
                return  response()->json(['code' => 205, 'msg' => $token_msg]);
            }
        } catch (\Exception $e) {
            return  response()->json(['code' => 205, 'msg' => '认证失败invalid_token']); //异常也失败
        }

        return $next($request); //验证通过
    }

    /**
     * 获取请求参数中的 token
     * @param request  object 请求参数对象
     */
    public function getToken($request)
    {
        $token = str_replace('Bearer ', '', $request->header('authorization')); //只能从header头获取

        return $token;
    }
}
